package com.atwisdom.star.core.dsl.modelClass.tank.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.UuidTool;
import com.atwisdom.star.common.vo.ModelType;
import com.atwisdom.star.common.vo.PageInfo;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstanceUtils;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierModel;
import com.atwisdom.star.core.dao.pojo.modelClass.logic.LogicModel;
import com.atwisdom.star.core.dao.pojo.modelClass.tank.TankInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.tank.TankInstanceHistory;
import com.atwisdom.star.core.dao.pojo.modelClass.tank.TankModel;
import com.atwisdom.star.core.dao.service.modelClass.tank.TankInstanceHistoryService;
import com.atwisdom.star.core.dao.service.modelClass.tank.TankInstanceService;
import com.atwisdom.star.core.dao.service.modelClass.tank.TankModelService;
import com.atwisdom.star.core.dsl.cache.ModelCacheDslService;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierModelDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.tank.TankInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.utils.ListHier;
import com.atwisdom.star.core.dsl.modelClass.utils.ListHierContent;
import com.atwisdom.star.core.dsl.modelClass.utils.QueryBuilder;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class TankInstanceDslServiceImpl implements TankInstanceDslService {

    private TankModelService tankModelService;
    private TankInstanceService tankInstanceService;
    private TankInstanceHistoryService tankInstanceHistoryService;
    private QueryBuilder queryBuilder;
    private ModelCacheDslService modelCacheDslService;
    private HierInstanceDslServiceImpl hierInstanceDslService;
    private HierModelDslServiceImpl hierModelDslService;

    @Autowired
    public void setModelCacheDslService(ModelCacheDslService modelCacheDslService) {
        this.modelCacheDslService = modelCacheDslService;
    }

    @Autowired
    public void setTankModelService(TankModelService tankModelService) {
        this.tankModelService = tankModelService;
    }

    @Autowired
    public void setTankInstanceService(TankInstanceService tankInstanceService) {
        this.tankInstanceService = tankInstanceService;
    }

    @Autowired
    public void setTankInstanceHistoryService(TankInstanceHistoryService tankInstanceHistoryService) {
        this.tankInstanceHistoryService = tankInstanceHistoryService;
    }

    @Autowired
    public void setQueryBuilder(QueryBuilder queryBuilder) {
        this.queryBuilder = queryBuilder;
    }
    @Autowired
    public void setHierInstanceDslService(HierInstanceDslServiceImpl hierInstanceDslService) {
        this.hierInstanceDslService = hierInstanceDslService;
    }
    @Autowired
    public void setHierModelDslService(HierModelDslServiceImpl hierModelDslService) {
        this.hierModelDslService = hierModelDslService;
    }

    /**
     * 查询全部摘要（通用）
     *
     * @return 返回搞要列表
     */
    @Override
    public List<JSONObject> queryAllInfo() {
        try {
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published", true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, null, "className,updateTime");
            List<TankInstance> list = tankInstanceService.list();
            List<JSONObject> jsonObjectList = new ArrayList<>();
            list.forEach(ins -> jsonObjectList.add(ins.getInfoJsonObject()));
            return jsonObjectList;
        } catch (Exception ex) {
            throw new BusinessException("999999", "无条件查询所有模型信息！");
        }
    }

    /**
     * 分页查询全部摘要（通用）
     *
     * @param pageNumber 参数
     * @param pageSize   参数
     * @param orderBy    参数
     * @return 返回全部搞要列表
     */
    @Override
    public PageInfo queryAllInfoByPage(int pageNumber, int pageSize, String orderBy, boolean needHier) {
        try {
            Page<TankInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published", true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper, true, needHier);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询摘要模型信息！", ex);
        }
    }

    /**
     * 查询全部数据（通用）
     *
     * @return 返回结果
     */
    @Override
    public List<JSONObject> queryAll() {
        try {
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published", true);
            queryBuilder.buildOrderBy(queryWrapper, null, "className,updateTime");
            List<TankInstance> list = tankInstanceService.list();
            list.forEach(l->{
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Tank.getCode(), l.getClassName(), l.getId());
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), l.getClassName());
                l.setHierModels(hierModels);
                l.setHierInstances(hierInstances);
            });

            return this.getTankInsJsonObjectList(list);
        } catch (Exception ex) {
            throw new BusinessException("999999", "无条件查询所有模型信息！");
        }
    }

    /**
     * 分页无条件查询模型信息
     *
     * @param pageNumber 参数
     * @param pageSize   参数
     * @param orderBy    参数
     * @return 返回值
     */
    @Override
    public PageInfo listAllByPage(int pageNumber, int pageSize, String orderBy, boolean needHier) {
        try {
            Page<TankInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published", true);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper, false, needHier);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 查询模型
     *
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy   排序参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> query(String condition, String className, String orderBy) {
        try {
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForTank(condition, className);
            orderBy =   this.transformOrderByForTank(condition, className, orderBy);
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            List<TankInstance> list = tankInstanceService.list(queryWrapper);
            list.forEach(l->{
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Tank.getCode(), l.getClassName(), l.getId());
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), l.getClassName());
                l.setHierInstances(hierInstances);
                l.setHierModels(hierModels);
            });
            return this.getTankInsJsonObjectList(list);
        } catch (Exception ex) {
            throw new BusinessException("999999", "查询模型失败！", ex);
        }
    }

    /**
     * 查询模型
     *
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy   排序参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> queryWithoutHier(String condition, String className, String orderBy) {
        try {
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForTank(condition, className);
            orderBy =   this.transformOrderByForTank(condition, className, orderBy);
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            List<TankInstance> list = tankInstanceService.list(queryWrapper);
            return this.getTankInsJsonObjectList(list);
        } catch (Exception ex) {
            throw new BusinessException("999999", "查询模型失败！", ex);
        }
    }

    /**
     * 按类名查找实例
     *
     * @param className 类名
     * @return 返回实例表
     */
    public List<TankInstance> queryByClassName(String className) {
        LambdaQueryWrapper<TankInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TankInstance::getClassName,className);
        wrapper.eq(TankInstance::getPublished,true);
        List<TankInstance> list = this.tankInstanceService.list(wrapper);
        List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), className);
        list.forEach(l->{
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Tank.getCode(), className, l.getId());
            l.setHierModels(hierModels);
            l.setHierInstances(hierInstances);
        });
        return list;
    }

    /**
     * 根据id获取实例数据
     *
     * @param id 主键id
     * @return 返回实例
     */
    public TankInstance queryById(Long id) {
        if (id!=null) {
            TankInstance instance = this.tankInstanceService.getById(id);
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), instance.getClassName());
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Tank.getCode(), instance.getClassName(), instance.getId());
            instance.setHierModels(hierModels);
            instance.setHierInstances(hierInstances);
            return instance;
        } else {
            return null;
        }
    }

    /**
     * 根据id获取实例数据
     *
     * @param id 主键id
     * @return 返回实例Json
     */
    @Override
    public JSONObject queryJsonById(Long id) {
        if (id!=null) {
            TankInstance tankInstance = this.tankInstanceService.getById(id);
            return getTankInsJsonObjectList(Arrays.asList(tankInstance)).get(0);
        } else {
            return null;
        }
    }

    /**
     * 根据id获取实例数据及关联的hier数据
     *
     * @param id 主键id
     * @return 返回实例
     */
    public TankInstance queryInsWithHierById(Long id) {
        if (id!=null) {
            TankInstance tankInstance = this.tankInstanceService.getById(id);
            if (tankInstance!=null) {
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), tankInstance.getId(),  tankInstance.getClassName(), null);
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), tankInstance.getClassName());
                tankInstance.setHierInstances(hierInstances);
                tankInstance.setHierModels(hierModels);
            }
            return tankInstance;
        } else {
            return null;
        }
    }

    /**
     * 根据id获取实例数据
     *
     * @param ids 主键ids
     * @return 返回实例
     */
    public List<JSONObject> queryByIds(List<Long> ids) {
        LambdaQueryWrapper<TankInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TankInstance::getId,ids);
        List<TankInstance> tankInstanceList = tankInstanceService.list(wrapper);
        tankInstanceList.forEach(l->{
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Tank.getCode(), l.getId(),  l.getClassName(), null);
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), l.getClassName());
            l.setHierInstances(hierInstances);
            l.setHierModels(hierModels);
        });
        return getTankInsJsonObjectList(tankInstanceList);

    }

    /**
     * 更新状态
     * @param id 实例id
     * @param statusCode 状态
     */
    @Override
    public void updateStatus(Long id, String statusCode) {
        TankInstance tankInstance = queryById(id);
        tankInstance.setSt0(statusCode);
        updateById(tankInstance);
    }

    /**
     * 查询实例容器hier
     *
     * @param id 参数
     * @return 返回hier
     */
    public JSONObject queryHierById(Long id) {
        try {
            TankInstance tankInstance = this.tankInstanceService.getById(id);
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Tank.getCode(), tankInstance.getClassName(), id);
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), tankInstance.getClassName());
            HierInstanceUtils hierInstanceUtils = new HierInstanceUtils(hierInstances, hierModels);
            return hierInstanceUtils.fetchHier();
        } catch (Exception ex) {
            throw new BusinessException("999999", "查询容器信息失败！");
        }
    }

    /**
     * 按条件分页查询实例摘要
     *
     * @param pageNumber 查询参数
     * @param pageSize   查询参数
     * @param condition  查询参数
     * @param className  查询参数
     * @param orderBy    排序参数
     * @return 返回值
     */
    public PageInfo queryInfoByPage(int pageNumber, int pageSize, String condition, String className, String orderBy, boolean needHier) {
        try {
            Page<TankInstance> pageInfo = new Page<>(pageNumber, pageSize);
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForTank(condition, className);
            orderBy =   this.transformOrderByForTank(condition, className, orderBy);
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper, true, needHier);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 按条件分页查询实例
     *
     * @param pageNumber 查询参数
     * @param pageSize   查询参数
     * @param condition  查询参数
     * @param className  查询参数
     * @param orderBy    排序参数
     * @return 返回值
     */
    public PageInfo queryByPage(int pageNumber, int pageSize, String condition, String className, String orderBy, boolean needHier) {
        try {
            Page<TankInstance> pageInfo = new Page<>(pageNumber, pageSize);
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForTank(condition, className);
            orderBy = this.transformOrderByForTank(condition, className, orderBy);
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper, false, needHier);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 按条件分页查询实例
     *
     * @param pageNumber 查询参数
     * @param pageSize   查询参数
     * @param condition  查询参数
     * @param className  查询参数
     * @param orderBy    排序参数
     * @return 返回值
     */
    public PageInfo queryByPage(int pageNumber, int pageSize, String condition, String className, String orderBy, String hierValueCondition) {
        try {
            Page<TankInstance> pageInfo = new Page<>(pageNumber, pageSize);
            condition = queryBuilder.transformOperator(condition);
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            condition = this.transformConditionForTank(condition, className);
            orderBy = this.transformOrderByForTank(condition, className, orderBy);
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            if (StrUtil.isNotBlank(hierValueCondition)) {
                hierValueCondition = hierValueCondition.replace("'$", "insValues->'$");
            }
            return getPageInfoResult(pageInfo, queryWrapper, false, hierValueCondition);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }


    /**
     * 添加模型
     *
     * @param type 参数
     * @param className 参数
     * @param name 参数
     * @return 返回值
     */
    @Override
    public JSONObject add(String type, String className,String name,JSONObject values) {
        TankInstance instance = buildNewTankInstance(type, className, name, values);
        TankModel tankModel = this.modelCacheDslService.queryModel(ModelType.Tank.getCode(), className);
        this.add(instance);
        return instance.getInsJsonObject(tankModel);
    }

    /**
     * 保存新实例
     * @param newInstance 新实例
     * @return 返回添加后的实例
     */
    public TankInstance add(TankInstance newInstance){
        if (StrUtil.isBlank(newInstance.getName())) {
            newInstance.setName(UuidTool.getUUID32());
        }
        this.tankInstanceService.save(newInstance);
        List<HierInstance> hierInstances = this.hierInstanceDslService.add(ModelType.Tank.getCode(), newInstance.getClassName(), newInstance.getId());
        List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), newInstance.getClassName());
        newInstance.setHierInstances(hierInstances);
        newInstance.setHierModels(hierModels);
        //添加历史
        TankInstanceHistory tankInstanceHistory = new TankInstanceHistory();
        BeanUtils.copyProperties(newInstance, tankInstanceHistory);
        tankInstanceHistory.setId(null);
        tankInstanceHistoryService.save(tankInstanceHistory);
        return newInstance;
    }

    /**
     * 保存新实例
     * @param insJson 新实例Json
     * @return 返回添加后的实例JSON
     */
    public JSONObject add(JSONObject insJson) {
        String className = insJson.getString("className");
        TankModel tankModel = this.modelCacheDslService.queryModel(ModelType.Tank.getCode(), className);

        TankInstance instance = new TankInstance(tankModel, insJson);
        this.add(instance);
        return instance.getInsJsonObject(tankModel);
    }


    /**
     * 构建新实例数据对象
     *
     * @param className 类名
     * @param name      名称
     * @return 返回构建的新实例
     */
    public TankInstance buildNewTankInstance(String className, String name) {
        return this.buildNewTankInstance("tank", className, name, null);
    }

    /**
     * 构建新实例数据对象
     * @param type 类型
     * @param className 类名
     * @param name 名称
     * @param values 实体值
     * @return 返回构建的新实例
     */
    public TankInstance  buildNewTankInstance(String type, String className,String name,JSONObject values){
        if (!existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
        if(values==null){
            values = new JSONObject();
        }
        TankModel tankModel = this.modelCacheDslService.queryModel(ModelType.Tank.getCode(), className);
        JSONObject insJsonObject = new JSONObject();
        insJsonObject.put("type", type);
        insJsonObject.put("name", name);
        insJsonObject.put("className", className);
        insJsonObject.put("published", true);
        insJsonObject.put("version", tankModel.getVersion());
        insJsonObject.put("values", values);
        insJsonObject.put("web", new JSONObject());
        insJsonObject.put("others", new JSONObject());

        return new TankInstance(tankModel, insJsonObject);
    }

    public TankInstance  buildNewTankInstance(JSONObject jsonObject){
        String className = jsonObject.getString("className");
        String type = jsonObject.getString("type");
        if (!existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
        TankModel tankModel = this.modelCacheDslService.queryModel(ModelType.Tank.getCode(), className);
        return new TankInstance(tankModel, jsonObject);
    }


    /**
     * 绑定实体到逻辑节点上，如果hier类型是list，需要创建新节点并绑定
     *
     * @param className 静态逻辑类名
     * @param nodeId    要绑定实体所在的节点
     * @param entityId  绑定实体的Id
     * @return 返回结静态逻辑实例json
     */
    public JSONObject bindEntityToHier(Long tankId, String className, String nodeId, Long entityId) {
        TankModel model = this.modelCacheDslService.queryModel(ModelType.Tank.getCode(), className);
        JSONObject hierProperties = model.getHierProperties();
        TankInstance tankInstance = this.tankInstanceService.getById(tankId);
        JSONObject hier = tankInstance.getHier();
        String type = hier.getString("type");
        JSONArray content = hier.getJSONArray("content");
        if(content==null){
            content = new JSONArray();
        }
        switch (type) {
            case "list":
                ListHier listHier = new ListHier(hierProperties);
                List<ListHierContent> listHierContent = listHier.getContent();
                listHierContent.get(0).getLink().put("id", entityId);
                listHierContent.get(0).setId(UuidTool.getUUID32());
                content.add(listHierContent.get(0));
                this.tankInstanceService.updateById(tankInstance);
                return tankInstance.getInsJsonObject(model);
            case "dictionary":
            case "tree":
            case "chain":
            case "treeChain":
                content.forEach(c -> {
                    JSONObject obj = (JSONObject) c;
                    String id = obj.getString("id");
                    if (id.equals(nodeId)) {
                        obj.getJSONObject("link").put("id", entityId);
                    }
                });
                this.tankInstanceService.updateById(tankInstance);
                return tankInstance.getInsJsonObject(model);
            default:
                break;

        }

        return tankInstance.getInsJsonObject(model);
    }

    /**
     * 绑定实体到逻辑节点上，如果hier类型是list，需要创建新节点并绑定
     *
     * @param nodeId   要绑定实体所在的节点
     * @param entityId 绑定实体的Id
     * @return 返回结静态逻辑实例json
     */
    public JSONObject unbindEntityToHier(Long tankId, String nodeId, Long entityId) {
        TankInstance tankInstance = this.tankInstanceService.getById(tankId);
        TankModel model = this.modelCacheDslService.queryModel(ModelType.Tank.getCode(), tankInstance.getClassName());
        JSONObject hier = tankInstance.getHier();
        String type = hier.getString("type");
        JSONArray content = hier.getJSONArray("content");
        if(content==null){
            content = new JSONArray();
        }
        switch (type) {
            case "list":
                int removeIndex = -1;
                for (int i = 0; i < content.size(); i++) {
                    JSONObject contentJson = content.getJSONObject(i);
                    JSONObject link = contentJson.getJSONObject("link");
                    String id = link.getString("id");
                    if (String.valueOf(entityId).equals(id)) {
                        removeIndex = i;
                    }
                }
                if (removeIndex > -1) {
                    content.remove(removeIndex);
                    hier.put("content",content);
                }
                this.tankInstanceService.updateById(tankInstance);
                return tankInstance.getInsJsonObject(model);
            case "dictionary":
            case "tree":
            case "chain":
            case "treeChain":
                content.forEach(c -> {
                    JSONObject obj = (JSONObject) c;
                    String id = obj.getString("id");
                    if (id.equals(nodeId)) {
                        obj.getJSONObject("link").put("id", "");
                    }
                });
                this.tankInstanceService.updateById(tankInstance);
                return tankInstance.getInsJsonObject(model);
            default:
                break;

        }

        return tankInstance.getInsJsonObject(model);
    }

    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObject 参数
     * @return 返回值
     */
    @Override
    public JSONObject updateById(JSONObject jsonObject) {
        try {
            TankInstance instance = this.buildUpdateInstance(jsonObject);
            TankModel tankModel = this.modelCacheDslService.queryModel(ModelType.Tank.getCode(), instance.getClassName());
            this.updateById(instance);
            return instance.getInsJsonObject(tankModel);
        }catch (Exception ex){
            throw new BusinessException("999999", "更新模型实例失败！");
        }
    }

    public void updateFieldNullById(JSONObject jsonObject){
        String className = jsonObject.getString("className");
        Long id = jsonObject.getLong("id");
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        JSONObject values = jsonObject.getJSONObject("values");
        JSONObject features = logicModel.fetchFeatures();
        UpdateWrapper<TankInstance> updateWrapper = new UpdateWrapper<>();
        // 遍历 JSONObject 对象
        for (String key : features.keySet()) {
            String v = values.getString(key);
            if(StringUtils.isBlank(v)){
                updateWrapper.set(key, null);
            }
        }
        updateWrapper.eq("id",id);
        tankInstanceService.update(updateWrapper);
    }

    public TankInstance  buildUpdateInstance(JSONObject jsonObject){
        String id = jsonObject.getString("id");
        if(StringUtils.isBlank(id)){
            throw new BusinessException("999999", "更新id为空操作失败！");
        }

        TankInstance sourceInstance = tankInstanceService.getById(id);
        if(sourceInstance==null){
            throw new BusinessException("999999", "要更新实例不存在，操作失败！");
        }
        JSONObject sourceInstanceJson = getTankInsJsonObjectList(Arrays.asList(sourceInstance)).get(0);
        String className = jsonObject.getString("className");
        String type = jsonObject.getString("type");
        if (!existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
        TankModel tankModel = this.modelCacheDslService.queryModel(ModelType.Tank.getCode(), sourceInstance.getClassName());
        return new TankInstance(tankModel,jsonObject,sourceInstanceJson.getJSONObject("values"));
    }

    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * @param tankInstance 参数
     * @return 返回值
     */
    public TankInstance updateById(TankInstance tankInstance){
        try {
            tankInstanceService.getBaseMapper().updateById(tankInstance);
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), tankInstance.getClassName());
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Tank.getCode(), tankInstance.getClassName(), tankInstance.getId());
            tankInstance.setHierInstances(hierInstances);
            tankInstance.setHierModels(hierModels);
            //添加历史
            TankInstance newTankInstance = this.tankInstanceService.getById(tankInstance.getId());
            TankInstanceHistory tankInstanceHistory = new TankInstanceHistory();
            BeanUtils.copyProperties(newTankInstance,tankInstanceHistory);
            tankInstanceHistory.setId(null);
            this.tankInstanceHistoryService.save(tankInstanceHistory);
            return tankInstance;
        }catch (Exception ex){
            throw new BusinessException("999999", "更新模型实例失败！");
        }
    }


    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObjectList 参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> updateByIds(List<JSONObject> jsonObjectList) {
        List<JSONObject> resultJsonList = new ArrayList<>();
        jsonObjectList.forEach(j -> {
            JSONObject jsonObject = this.updateById(j);
            resultJsonList.add(jsonObject);

        });
        return resultJsonList;
    }


    /**
     * 按类型和类名更新模型实例（配置阶段）
     *
     * @param jsonObject 类型
     * @return 返回模型记录
     */
    @Override
    public List<JSONObject> updateClassName(JSONObject jsonObject) {
        String type = jsonObject.getString("type");
        String className = jsonObject.getString("className");
        if (StringUtils.isBlank(type) || StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "更新模型实例：type,className都不能为空！");
        }

        if (!this.existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在，更新模型实例失败！");
        }

        try {
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("type", type);
            queryWrapper.eq("published", true);
            List<TankInstance> instances = this.tankInstanceService.list(queryWrapper);
            List<JSONObject> resList = new ArrayList<>();
            instances.forEach(ins -> {
                jsonObject.put("id", ins.getId());
                JSONObject upJsonObject = this.updateById(jsonObject);
                resList.add(upJsonObject);
            });
            return resList;
        } catch (Exception ex) {
            throw new BusinessException("999999", "更新模型类型和类名", ex);
        }
    }


    /**
     * 按ids删除模型
     *
     * @param ids id列表
     * @return 返回结果
     */
    public boolean deleteByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，删除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            queryWrapper.eq("b7", false);
            //删除实例
            this.tankInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByContainerIdList(ModelType.Tank.getCode(), ids);
            this.hierInstanceDslService.deleteByLinkIdList(ModelType.Tank.getCode(), ids);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }
    }

    /**
     * 接className删除
     * 1、删除实例、2、删除历史 3、更新redis
     *
     * @param className 模型类名
     * @return 返回值
     */
    @Override
    public boolean deleteByClassName(String className) {
        if (StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "模型类名称不能为空,删除模型实例失败！");
        }
        //删除缓存
        try {
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("published", true);
            //删除模型
            this.tankInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByClassName(ModelType.Tank.getCode(), className);
            this.hierInstanceDslService.deleteByLinkClassName(ModelType.Tank.getCode(), className);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", String.format("删除模型%s失败!", className), ex);
        }
    }

    /**
     * 批量删除
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean deleteByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型实例失败！");
        }
        try {
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除实例
            this.tankInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByClassNameList(ModelType.Tank.getCode(), classNames);
            this.hierInstanceDslService.deleteByLinkClassNameList(ModelType.Tank.getCode(), classNames);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "模型类名称列表删除模型失败！");
        }
    }

    /**
     * 按Id 废除模型
     *
     * @param ids 参数
     * @return 返回结果
     */
    public boolean repealByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，废除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<TankInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            //删除实例
            this.tankInstanceService.remove(queryWrapper);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }

    }

    /**
     * 批量废除
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean repealByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型失败！");
        }
        try {
            QueryWrapper<TankModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除模型
            this.tankModelService.remove(queryWrapper);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "模型类名称列表删除模型实例失败！");
        }
    }

    /**
     * 获取分页查询
     *
     * @param pageInfo     分页信息
     * @param queryWrapper 查询wrapper
     * @return 返回结果
     */
    private PageInfo getPageInfoResult(Page<TankInstance> pageInfo, QueryWrapper<TankInstance> queryWrapper, boolean isInfo, boolean needHier) {
        Page<TankInstance> queryPage = tankInstanceService.page(pageInfo, queryWrapper);
        List<TankInstance> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList;
        if (isInfo) {
            jsonObjectList = this.getTankInsInfoJsonObjectList(records);
        } else {
            if (needHier) {
                records.forEach(r->{
                    List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Tank.getCode(), r.getClassName(), r.getId());
                    List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), r.getClassName());
                    r.setHierInstances(hierInstances);
                    r.setHierModels(hierModels);
                });
            }
            jsonObjectList = this.getTankInsJsonObjectList(records);
        }
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        return PageInfo.of(queryPageDTO);
    }

    /**
     * 获取分页查询
     *
     * @param pageInfo     分页信息
     * @param queryWrapper 查询wrapper
     * @return 返回结果
     */
    private PageInfo getPageInfoResult(Page<TankInstance> pageInfo, QueryWrapper<TankInstance> queryWrapper, boolean isInfo, String hierCondition) {
        Page<TankInstance> queryPage = tankInstanceService.page(pageInfo, queryWrapper);
        List<TankInstance> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList;
        if (isInfo) {
            jsonObjectList = this.getTankInsInfoJsonObjectList(records);
        } else {
            records.forEach(r->{
                List<HierInstance> hierInstances = hierInstanceDslService.queryByContainerId(ModelType.Tank.getCode(), r.getId(), r.getClassName(), hierCondition);
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Tank.getCode(), r.getClassName());
                r.setHierInstances(hierInstances);
                r.setHierModels(hierModels);
            });
            jsonObjectList = this.getTankInsJsonObjectList(records);
        }
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        return PageInfo.of(queryPageDTO);
    }

    /**
     * 检查模型是否存在
     *
     * @param type      类型
     * @param className 类名称
     * @return 返回是否存，true 存在，false 不存在
     */
    private boolean existModel(String type, String className) {
        QueryWrapper<TankModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
        queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
        queryWrapper.eq("published", true);
        long count = this.tankModelService.count(queryWrapper);
        return count > 0;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getTankInsInfoJsonObjectList(List<TankInstance> instances) {
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            JSONObject infoJsonObject = ins.getInfoJsonObject();
            jsonList.add(infoJsonObject);

        });
        return jsonList;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getTankInsJsonObjectList(List<TankInstance> instances) {
        List<TankModel> models = this.tankModelService.list();
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            TankModel tankModel = models.stream().filter(m -> m.getClassName().equalsIgnoreCase(ins.getClassName())).findFirst().orElse(null);
            JSONObject insJsonObject = ins.getInsJsonObject(tankModel);
            jsonList.add(insJsonObject);
        });
        return jsonList;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition 参数
     * @param className 参数
     */
    public String transformConditionForTank(String condition, String className) {
        if (StringUtils.isBlank(condition)) {
            return "";
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }
        if (StringUtils.isBlank(className)) {
            return condition;
        }
        if (StringUtils.isNotBlank(className) && StringUtils.isNotBlank(condition)) {
            TankModel tankModel = modelCacheDslService.queryModel(ModelType.Tank.getCode(), className);
            if (tankModel != null) {
                List<JSONObject> featureProperties = tankModel.fetchFeatureProperties();
                for (JSONObject item : featureProperties) {
                    String name = item.getString("name");
                    String code = item.getString("code");
                    // condition = condition.replaceAll(name, code);
                    condition = condition.replaceAll("(?<!['%a-z\\d_\\u4e00-\\u9fa5])"+name, code);
                }
                List<JSONObject> featureNoProperties = tankModel.fetchNonFeaturesProperties();
                for (JSONObject item : featureNoProperties) {
                    String name = item.getString("name");
                    condition = condition.replaceAll("(?<!['%a-z0-9_\\u4e00-\\u9fa5])"+name,
                            java.util.regex.Matcher.quoteReplacement("JSON_EXTRACT(insValues,'$.")+name+
                                    "')");
                }
            }
        }
        return condition;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition 取className 条件
     * @param className 类名
     * @param orderBy   排序参数
     */
    public String transformOrderByForTank(String condition, String className, String orderBy) {
        if (StringUtils.isBlank(orderBy)) {
            return "";
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }

        if (StringUtils.isBlank(className)) {
            return orderBy;
        }
        orderBy = orderBy.replaceAll(" ", "");
        TankModel tankModel = modelCacheDslService.queryModel("tank", className);
        List<JSONObject> featureProperties = tankModel.fetchFeatureProperties();
        for (JSONObject item : featureProperties) {
            String name = item.getString("name");
            String code = item.getString("code");
            orderBy = orderBy.replaceAll(name, code);
        }
        return orderBy;
    }
}
